// pages/register/register.js
var app = getApp();
// var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
// var qqmapsdk;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    myHttp: app.globalData.myHttp,
    currentCity: '武汉市',
    currentProvince: '武汉',
    citys: ['武汉市'],
    latitude: "30.499983",
    longitude: "114.434651",
    index: 0,
    currentTab: 0,
    navbar: [
      "距离排序", "预约量排序", "最近预约"
    ],
    hospitalsByDistance: [],
    hospitalsByCount: [],
    selectedHospital: {},
    recentAppointments: [],
    distanceList: [],
    tapIndex: "",
    showMask: false,
    nowCity: '',
    secHosShow: false,
    noHospital: true, //暂无医院数据
    loadingHidden: true, //加载动画
    loading: false, //加载更多
    loadingComplete: false, //加载完成
    page: 1, //默认当前页数
    totalPage: '', //总条数
  },


  //tab标签页选择
  navbarTap: function (e) {
    var that = this
    var currentTab = e.currentTarget.dataset.idx
    //点击距离排序
    if (currentTab == 0) {
      this.setData({
        hospitalsByDistance: [],
        currentTab: e.currentTarget.dataset.idx,
        loadingHidden: false,
        loading: false,
        loadingComplete: false
      })
      that.getLocation()
    }
    //点击预约量排序
    if (currentTab == 1) {
      this.setData({
        hospitalsByCount: [],
        currentTab: e.currentTarget.dataset.idx,
        loadingHidden: false,
        loading: false,
        loadingComplete: false
      })
      // 查询医院列表
      that.queryHospitalList(currentTab, true)
    }
    //点击最近预约
    if (currentTab == 2) {
      var id = 'tab2' // 或者 e.target.id 获取点击元素的 ID 值
      wx.createSelectorQuery().select('#' + id).boundingClientRect(res => {
        // 调用自定义组件 popover 中的 onDisplay 方法
        this.popover.onDisplay(res);
      }).exec();
      
      var user = wx.getStorageSync("user")
      if (user == '' || user == undefined || user == null) {
        wx.navigateTo({
          url: '../login/login',
        })
        wx.showToast({
          title: '请先登录',
          icon: 'none',
          duration: 2000
        })
      } else {
        if(this.popover.data.visible){
          return;
        }
        that.setData({
          recentAppointments: [],
          showMask: true
        })
        wx.request({
          url: this.data.myHttp + '/hospital/recentAppointment/' + user.userID,
          method: "GET",
          header: {
            'content-type': 'application/json',
          },
          success: function (res) {
            that.setData({
              recentAppointments: res.data.obj
            })
          }
        })
      }
    }
  },

  onClickA() {
    this.popover.onHide();
  },

  //点击改变城市
  bindPickChange: function (e) {
    var that = this
    var curCity = this.data.citys[e.detail.value]
    this.setData({
      hospitalsByCount: [],
      hospitalsByDistance: [],
      index: e.detail.value,
      currentCity: curCity,
      loadingHidden: false
    })
    that.queryHospitalList(that.data.currentTab, true)
  },

  //搜索医院/医生/科室
  bindSearch() {
    wx.navigateTo({
      url: '../search/search?city=' + JSON.stringify(this.data.currentCity)
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      currentUser: wx.getStorageSync("user"),
      loadingHidden: false
    })
    //获取经纬度
    that.getLocation()
    //获取城市
    that.getCities()
    //获取用户信息
    that.login()
  },

  // 获取当前经纬度信息
  getLocation: function () {
    var that = this
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var lat = res.latitude.toString()
        var lng = res.longitude.toString()
        console.log("定位获取经纬度信息", lat, lng)
        that.setData({
          latitude: lat.substring(0, lat.indexOf(".") + 6),
          longitude: lng.substring(0, lng.indexOf(".") + 6)
        })
      },
      fail(res) {
        wx.showModal({
          title: '提示',
          content: "获取地理位置失败",
          confirmText: "查看授权",
          success(res) {
            if (res.confirm) {
              console.log('用户点击查看授权')
              wx.openSetting({
                success(res) {}
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          },
        })
      },
      complete() {
        // 查询医院列表
        that.queryHospitalList(that.data.currentTab, true)
      }
    })
  },

  //获取城市列表
  getCities: function () {
    var that = this
    wx.request({
      url: this.data.myHttp + '/baseCities/getCities',
      method: "GET",
      header: {
        'content-type': 'application/json',
      },
      success(res) {
        var list = []
        for (let i in res.data.obj) {
          list.push(res.data.obj[i].city)
        }
        that.setData({
          citys: list,
          noHospital: true
        })
      },
      complete: (res) => {
        if (res.statusCode != 200) {
          that.setData({
            citys: ['武汉市']
          })
        }
      }
    })
  },

  //分页查询医院列表
  queryHospitalList: function (currentTab, isPage) {
    var that = this
    var orderByName = (currentTab == 0) ? 'isAsc=1' : "isCount=1"
    //下拉舒心
    if (isPage === true) {
      that.setData({
        page: 1,
        loading: false,
        loadingComplete: false
      })
    } else {
      var num = that.data.page + 1
      if (num <= that.data.totalPage) {
        that.setData({
          page: num
        })
      } else if (num > that.data.totalPage) {
        that.setData({
          loading: false,
          loadingComplete: true
        })
        return;
      }
    }
    wx.request({
      url: this.data.myHttp + '/hospital/getHospitalPage?' + orderByName,
      method: "GET",
      header: {
        'content-type': 'application/json',
      },
      data: {
        "type": 0,
        "lng": that.data.longitude,
        "lat": that.data.latitude,
        "Province": that.data.currentCity,
        "current": that.data.page,
        "size": 8,
      },
      success: function (res) {
        if (res.data.success) {
          var records = res.data.obj.records;
          if (records.length != 0) {
            var hospitals = []
            if (currentTab == 0) {
              hospitals = that.splitArray(res.data.obj.records, that.data.hospitalsByDistance)
              var distanceList = []
              for (let i in hospitals) {
                distanceList[i] = parseInt(hospitals[i].distance / 100) / 10
              }
              that.setData({
                hospitalsByDistance: hospitals,
                distanceList: distanceList,
                totalPage: res.data.obj.pages,
                noHospital: true,
                loadingHidden: true
              })
            } else {
              hospitals = that.splitArray(res.data.obj.records, that.data.hospitalsByCount)
              that.setData({
                hospitalsByCount: hospitals,
                totalPage: res.data.obj.pages,
                noHospital: true,
                loadingHidden: true
              })
            }
          }else{
            that.setData({
              noHospital: false,
              loadingHidden: true
            })
          }
        } else {
          that.setData({
            noHospital: false,
            loadingHidden: true
          })
        }
      },
      complete: (res) => {
        if (res.statusCode != 200) {
          that.setData({
            noHospital: false,
            loadingHidden: true
          })
        }
        // wx.hideLoading()
      }
    })
  },

  login: function(){
    var user = wx.getStorageSync("user")
    var userID = user.userID;
    if(!userID){
      return;
    }
    wx.request({
      url: this.data.myHttp + '/user/getUserById?',
      method: "GET",
      header: {
        'content-type': 'application/json',
      },
      data: {
        "id": userID,
      },
      success: function (res) {
        console.log(res.data)
        var data = res.data
        if (data.success) {
          // 缓存用户数据
          wx.setStorageSync('user', data.obj.user)
          //token
          wx.setStorageSync('token',data.obj.token)
          // 保存用户账号
          getApp().globalData.userPhone = data.obj.user.userPhone;
        }
      },
      complete: (res) => {
        if (res.statusCode != 200) {
          that.setData({
            noHospital: false,
            loadingHidden: true
          })
        }
        // wx.hideLoading()
      }
    })
  },

  //点击医院跳转进医院介绍
  bindViewTapToHospital1: function (e) {
    var hospital = e.currentTarget.dataset.hospital
    this.setData({
      selectedHospital: e.currentTarget.dataset.hospital,
      tapIndex: e.currentTarget.dataset.index
    })
    if (hospital.secondHospitalList != null && hospital.secondHospitalList.length > 1) {
      if (this.data.secHosShow) {
        this.setData({
          secHosShow: false
        })
      } else {
        this.setData({
          secHosShow: true
        })
      }
      return
    }
    wx.navigateTo({
      url: '../hospitalIntroduction/hospitalIntroduction?selectedHospitalId=' + JSON.stringify(this.data.selectedHospital.id)
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完
   */
  onReady: function () {
    // 生命周期函数 onReady 中获取自定义的 popover 组件，根据id获取
    this.popover = this.selectComponent('#popover');

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 调用自定义组件 popover 中的 onHide 方法
    this.popover.onHide();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this
    that.setData({
      page: 1,
      hospitalsByCount: [],
      hospitalsByDistance: [],
      loadingHidden: false
    })
    // 标题栏显示刷新图标，转圈圈
    wx.showNavigationBarLoading()
    //加载数据
    that.queryHospitalList(that.data.currentTab, true)
    that.login()
    setTimeout(() => {
      // 标题栏隐藏刷新转圈圈图标
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh();
    }, );
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this
    if (!that.data.loadingComplete) {
      that.setData({
        loading: true
      })
    }
    setTimeout(() => {
      that.queryHospitalList(that.data.currentTab)
    }, 2000);
  },

  /**
   * 合并数组
   */
  splitArray: function (list, sp) {
    if (typeof list != 'object') return [];
    if (sp === undefined) sp = [];
    for (var i = 0; i < list.length; i++) {
      sp.push(list[i]);
    }
    return sp;
  },
})